package web;

import helperclasses.DbUtil;
import helperclasses.InitialParams;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import TreeStructure.DOMParser;

import model.UnitateMasura;

/**
 * Servlet implementation class DBconnectionListener
 */
public class DBconnectionListener extends HttpServlet implements
		ServletContextListener {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DBconnectionListener() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext sc = arg0.getServletContext();
		String userName = sc.getInitParameter("dbuserName");
		String password = sc.getInitParameter("dbpassword");
		String url = sc.getInitParameter("dburl");

		DbUtil.setValues(userName, password, url);

		try {
			DOMParser dp = new DOMParser();
			sc.setAttribute("tree", dp.getTree());
			UnitateMasura um = new UnitateMasura();
			sc.setAttribute("unimasura", um.getuMasura());
			InitialParams initparams = new InitialParams();
			//initparams.getInitParamsFromFile(sc.getInitParameter("propfilepath")); 	get initparams from prop file
			initparams.getInitParamsFromDB();
			sc.setAttribute("InitialParams", initparams);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		// try {
		// Connection myConn = (Connection)
		// getServletContext().getAttribute("myConn");
		// java.sql.Statement myStatement = (java.sql.Statement)
		// getServletContext().getAttribute("myStatement");
		//
		// myStatement.close();
		// myConn.close();
		// System.out.println("1SQL connection closed succesffuly");
		// } catch (SQLException e) {
		// e.printStackTrace();
		// }
		// System.out.println("2SQL connection closed succesffuly");

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
